import {Injectable} from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import {adSystemApiUrl, tuikeSystemUrl} from '../../../config/api';
import {HttpService} from './http.service';

@Injectable()
export class LoginService {

  constructor(private http: Http, private httpService: HttpService) {

  }

  doLogin(username, password) {
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify({account: username, password: password});
    return this.http.post(tuikeSystemUrl + '/api/v1/admin/rbac/login', body, options).map(response => response.json());
  }

  register(redirectMsg) {
    const url = adSystemApiUrl + '/v1/member/auth/register';
    return this.httpService.httpPostAuth(url, redirectMsg).map(data => data);
  }

  smsSend(mobile: number, type: number) {
    const url = adSystemApiUrl + '/v1/common/sms/send';
    return this.httpService.httpPostAuth(url, {mobile: mobile, type: type}).map(data => data);
  }

  getTableId() {
    const url = adSystemApiUrl + '/v1/common/captcha/get_table_id';
    return this.httpService.httpGetAuth(url).map(data => data);
  }

  checkCode(code, table_id) {
    const url = adSystemApiUrl + `/v1/common/captcha/api_check?code=${ code }&table_id=${ table_id }`;
    return this.httpService.httpGetAuth(url).map(data => data);
  }

  passedit(passeditMsg) {
    const url = adSystemApiUrl + '/v1/member/auth/passedit';
    return this.httpService.httpPostAuth(url, passeditMsg).map(data => data);
  }

  doLoginAdmin(account, password) {
    const url = tuikeSystemUrl + '/api/v1/admin/rbac/login';
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const body = JSON.stringify({user_name: account, password: password});
    return this.httpService.httpPostAuth(url, body,options).map(data => data);
  }

  getAdminShowTree() {
    const url = `${tuikeSystemUrl}/api/v1/admin/rbac/get_admin_show_permissions`;
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    return this.httpService.httpPostAuth(url,{},options).map(data => data);
  }

  canVisitCheck(node) {
    let flag = false;
    if(window.localStorage.getItem('hidedList')) {
      let hidedList = JSON.parse(window.localStorage.getItem('hidedList'));
      hidedList.map((e,i) => {
        if(e['node'] == node) {
          flag = true;
        }
      });
      return flag;
    } else {
      return flag;
    }
  }
}
